package xueqiu

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
)

type StockBuy struct {
	Id   int64
	Code string
}

func (sb StockBuy) Init() {
	stockBuyList := []StockBuy{}
	Db.Table("stock_buy").Find(&stockBuyList)

	for {

		for _, v := range stockBuyList {

			url := "https://xueqiu.com/S/" + v.Code
			sb.getNowPrice(url)
		}
		fmt.Println()
		time.Sleep(time.Duration(2) * time.Second)
	}
}

func (sb StockBuy) getNowPrice(url string) {
	res, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		fmt.Println("网络未正常响应httpCode:")
		fmt.Println(res.StatusCode)
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)

	if err != nil {
		fmt.Println(err)
	}

	//现价
	doc.Find(".stock-current").Each(func(i int, s *goquery.Selection) {
		text := s.Find("strong").Text()
		price := strings.TrimLeft(text, "¥")
		fmt.Printf("%s \n", string(price))
	})

	doc.Find(".stock-change").Each(func(i int, s *goquery.Selection) {
		change := s.Text()
		changeArr := strings.Split(change, " ")
		a, _ := strconv.ParseFloat(changeArr[0], 64)
		if a > 0 {
			fmt.Println("+")
		} else if a == 0 {
			fmt.Println("=")
		} else {
			fmt.Println("-")
		}
	})
}
